package cn.time1024.time_app.ui.player

import android.net.Uri
import android.os.Bundle
import android.widget.MediaController
import android.widget.Toast
import android.view.View
import android.widget.ProgressBar
import android.widget.VideoView
import androidx.appcompat.app.AppCompatActivity
import cn.time1024.time_app.R

/**
 * 视频播放器页面：
 * - 使用原生 VideoView + MediaController 播放网络视频直链；
 * - 在准备阶段显示进度，准备完成后自动开始播放；
 * - 简洁稳定，无需额外依赖，适合快速集成。
 */
class VideoPlayerActivity : AppCompatActivity() {

    private var videoView: VideoView? = null
    private var progress: ProgressBar? = null
    private var lastPosition: Int = 0

    /**
     * 创建界面并初始化播放器组件。
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_video_player)

        videoView = findViewById(R.id.videoView)
        progress = findViewById(R.id.progress)

        val url = intent.getStringExtra(EXTRA_URL)
        if (url.isNullOrBlank()) {
            Toast.makeText(this, "未获取到视频地址", Toast.LENGTH_SHORT).show()
            finish()
            return
        }

        setupVideo(url)
    }

    /**
     * 配置 VideoView 播放给定 URL。
     */
    private fun setupVideo(url: String) {
        try {
            progress?.visibility = View.VISIBLE
            val controller = MediaController(this)
            controller.setAnchorView(videoView)
            videoView?.setMediaController(controller)
            videoView?.setVideoURI(Uri.parse(url))
            videoView?.setOnPreparedListener { mp ->
                progress?.visibility = View.GONE
                mp.isLooping = false
                if (lastPosition > 0) {
                    videoView?.seekTo(lastPosition)
                }
                videoView?.start()
            }
            videoView?.setOnErrorListener { _, what, extra ->
                progress?.visibility = View.GONE
                Toast.makeText(this, "播放失败($what/$extra)", Toast.LENGTH_SHORT).show()
                false
            }
        } catch (e: Exception) {
            progress?.visibility = View.GONE
            Toast.makeText(this, "初始化播放器出错：${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 页面进入前台时恢复播放。
     */
    override fun onStart() {
        super.onStart()
        if (lastPosition > 0) {
            videoView?.seekTo(lastPosition)
        }
        if (videoView?.isPlaying == false) {
            videoView?.start()
        }
    }

    /**
     * 页面离开前台时记录进度并暂停。
     */
    override fun onStop() {
        super.onStop()
        try {
            lastPosition = videoView?.currentPosition ?: 0
            videoView?.pause()
        } catch (_: Exception) {
        }
    }

    companion object {
        const val EXTRA_URL = "url"
    }
}